#include "gamesession.h"

GameSession::GameSession()
    : m_users()
    , m_user_HeadImgUrl()
    , m_gifts()
    , m_game_switch(false)
    , m_steam_swith(true)
    , m_timer_game(new QTimer(this))
    , m_reply(nullptr)
    , m_codeArray()
    , m_standby_codeArray()
    , m_manager(new QNetworkAccessManager(this))
    , m_anchorId("")
{
    connect(m_timer_game, &QTimer::timeout, this, &GameSession::on_send_codes);
}


GameSession::~GameSession()
{
    // 怀疑大量发送数据退出之后进程没杀干净，所以添加以下代码，可注释掉
    if (m_timer_game) {
        m_timer_game->stop();
        qDebug() << "Timer stopped";
    }

    // 中止并清理未完成的网络请求
    if (m_reply) {
        m_reply->abort();
        m_reply->deleteLater();
        m_reply = nullptr;
        qDebug() << "Network reply aborted and deleted";
    }

    // 清理 QNetworkAccessManager
    if (m_manager) {
        m_manager->deleteLater();
        m_manager = nullptr;
        qDebug() << "Network manager deleted";
    }
}

void GameSession::clear_users()
{
    m_users.clear();
}


void GameSession::join_users(const QString &user_nickname, const QString &user_id)
{
    m_users.insert(user_nickname, user_id);
    emit player_join(user_nickname, user_id);
}


int GameSession::get_users_count()
{
    return m_users.size();
}


void GameSession::change_game_switch(const bool &is_stop)
{
    m_game_switch = is_stop;
}


// 通过ID获取玩家名字
QString GameSession::get_user_name(const QString &user_id)
{
    QString str = "没有找到玩家名";

    for (auto item = m_users.begin(); item != m_users.end(); item++) {
        if (item.value() == user_id) {
            str = item.key();
        }
    }

    return str;
}


QString GameSession::find_users(const int& index)
{
    QString str = "没有找到玩家名";

    for (auto it = m_users.constBegin(); it != m_users.constEnd(); ++it) {
        if (it.value() == QString("%1").arg(index, 4, 10, QChar('0'))) {
            return it.key();
        }
    }

    return str;
}




// 发送弹幕数据
void GameSession::on_send_codes()
{
    m_steam_swith = !m_steam_swith;
    QJsonArray& arrayToSend = m_steam_swith ? m_standby_codeArray : m_codeArray;

    if (m_anchorId.isEmpty() || m_Uuid.isEmpty()) {
        qDebug() << "主播ID或本局ID为空无法传输";
        return;
    }

    if (m_game_switch) {
        game(arrayToSend);
        qDebug() << "游戏函数执行完毕";
    }

    if (arrayToSend.size() <= 0) {
        return;
    }

    QJsonArray tmp = fill_robot(arrayToSend);
    arrayToSend = QJsonArray();

    if (tmp.isEmpty()) {
        return;
    }

    QJsonArray finalArray;

    for (const auto& item : tmp) {
        QJsonObject obj = item.toObject();
        obj["anchorId"] = m_anchorId;

        if (obj["user_nickname"] == "")
        {// 添加用户名称
            QString userId = obj["user_id"].toString();
            for (auto it = m_users.begin(); it != m_users.end(); ++it)
            {
                if (it.value() == userId) {
                    obj["user_nickname"] = it.key();
                    break;
                }
            }
        }

        obj["Uuid"] = m_Uuid;
        finalArray.append(obj);
    }

    QJsonDocument jsonDoc(finalArray);
    QByteArray jsonData = jsonDoc.toJson();

    QUrl url(Config::instance().upDanmuUrl());
    QNetworkRequest request(url);

    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");

    if (m_reply != nullptr) {
        qDebug() << "取消旧请求";
        m_reply->abort();        // 取消旧请求
        delete m_reply;
    }

    m_reply = m_manager->post(request, jsonData);
}


// 筛选掉机器人弹幕数据
QJsonArray GameSession::fill_robot(const QJsonArray& array)
{
    QJsonArray arr;
    QRegularExpression regex(tr("^【测试用】机器人-\\d+$"));
    QSet<QString> set;

    // 找出机器人序号
    for (auto it = m_users.begin(); it != m_users.end(); ++it)
    {
        const QString& key = it.key();
        if (regex.match(key).hasMatch()) {
            set.insert(it.value());
        }
    }

    for (QJsonArray::const_iterator it = array.begin(); it != array.end(); ++it)
    {
        QJsonObject jsonObj = it->toObject();
        QString id = jsonObj.value("user_id").toString();

        if (!set.contains(id)) {
            arr.append(jsonObj);
        }
    }

    return arr;
}


// 游戏函数
void GameSession::game(const QJsonArray& array)
{

}


// 开始游戏
void GameSession::start_game()
{
    m_timer_game->start(Config::instance().autoUploadInterval());
    m_game_switch = true;
}


// 重启游戏
void GameSession::rebot_game()
{
    qDebug() << "重启游戏";
    m_game_switch = false;
    emit on_reboot_game();
}


// 结束游戏
void GameSession::quit_game()
{
    qDebug() << "停止游戏";
    m_game_switch = false;
    out_cache();
}


// 输出缓存
void GameSession::out_cache()
{
    m_timer_game->stop();
    on_send_codes();
    on_send_codes();
}


QMap<QString, QString> GameSession::get_users()
{
    return m_users;
}


QString GameSession::append_user(const int &code, const TiktokGiftInfo &giftInfo)
{
    QJsonObject obj;
    obj["gift_count"]    = giftInfo.giftCount;
    obj["config_id"]     = code;
    obj["gift_name"]     = giftInfo.giftName;
    obj["gift_price"]    = giftInfo.giftPrice;
    obj["game_id"]       = Config::instance().gameId();
    obj["user_nickname"] = giftInfo.userName;
    obj["Uuid"]          = m_Uuid;

    QString user_count;

    if (code == 0) {
        obj["user_id"] = "0";
    }
    else {
        if (!m_users.contains(giftInfo.userName)) {
            obj["user_id"] = user_count = QString("%1").arg(m_users.size() + 1, 4, 10, QChar('0'));

            m_user_HeadImgUrl.insert(user_count, giftInfo.userAvatar); // 保存用户头像
            m_users.insert(giftInfo.userName, user_count);

            emit player_join(giftInfo.userName, user_count);
        }
        else { // 如果存在查找用户ID，并输出
            obj["user_id"] = m_users.value(giftInfo.userName);
        }
    }

    if (m_steam_swith) {
        m_codeArray.append(obj);
    }
    else {
        m_standby_codeArray.append(obj);
    }

    return QString("%1，%2，%3*%4")
        .arg(obj["user_id"].toString())
        .arg(giftInfo.userName)
        .arg(giftInfo.giftName)
        .arg(giftInfo.giftCount);
}


void GameSession::additem(QString playerId, QString team, QString content, const int progress, QString prefix, int customAvatarIndex)
{
    QString user_name("");
    QString user_HeadImgUrl;

    for (auto item = m_users.begin(); item != m_users.end(); item++)
    {
        if (item.value() == playerId)
        {
            user_name = item.key();
            if (customAvatarIndex != 0) {
                user_HeadImgUrl = QString(Config::instance().customAvatarUrl()).arg(customAvatarIndex);
            } else {
                user_HeadImgUrl = m_user_HeadImgUrl.value(playerId, "");
            }
            emit add_item(playerId, user_name, user_HeadImgUrl, team, content, progress, prefix);
            break;
        }
    }
}


void GameSession::delitem(QString playerId)
{
    QString user_name("");
    for (auto item = m_users.begin(); item != m_users.end(); item++)
    {
        if (item.value() == playerId)
        {
            user_name = item.key();
            emit del_item(playerId, user_name);
            break;
        }
    }
}


// 发送击杀播报
void GameSession::killBroadcast(const QString killerId, const QString victimId, const int killVoice)
{
    Player killer, victim;

    killer.name = get_user_name(killerId);
    killer.avatar = get_user_avatar(killerId);
    killer.id = killerId;

    victim.name = get_user_name(victimId);
    victim.avatar = get_user_avatar(victimId);
    victim.id = victimId;

    emit show_killBroadcast(killer, victim, killVoice);
}


void GameSession::clearKillBroadcast()
{
    emit clear_killBroadcast();
}


QString GameSession::get_user_avatar(QString playerId)
{
    return m_user_HeadImgUrl[playerId] == "" ? "https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png" : m_user_HeadImgUrl[playerId];
}


// 清空游戏 UI
void GameSession::clearUI()
{
    emit clear_UI();
}

// 清空弹窗
void GameSession::clearPopover()
{
    emit clear_Popover();
}


void GameSession::setAnchorId(QString anchorId)
{
    m_anchorId = anchorId;
}


void GameSession::setGifts(QString giftId, QString giftName)
{
    m_gifts.insert(giftId, giftName);
}


void GameSession::set_Uuid(QString Uuid)
{
    m_Uuid = Uuid;
}


// 显示弹窗调用函数
void GameSession::on_show_win(const QString &playerId, const QString &team, const QString &content)
{
    QString user_name = get_user_name(playerId);
    if (user_name == "") {
        qDebug() << "没有找到玩家";
        return;
    }
    QString user_HeadImgUrl = m_user_HeadImgUrl.value(playerId, "没有找到头像");

    emit show_win(user_name, user_HeadImgUrl, team, content);
}


// 显示礼物调用函数
void GameSession::on_show_gift(const QString &playerId, const QString &team, const QString &content)
{
    QString user_name = get_user_name(playerId);
    if (user_name == "") {
        qDebug() << "没有找到玩家";
        return;
    }
    QString user_HeadImgUrl = m_user_HeadImgUrl.value(playerId, "没有找到头像");

    emit show_gift(user_name, user_HeadImgUrl, team, content);
}

